<template>
  <van-popup v-model="popupShow" position="top" @close="hide">
    <div class="popup-wrap">
      <div class="top-wrap">
        <span>{{ $t('搜索') }}</span>
        <van-icon name="cross" size="28" @click="hide"/>
      </div>
      <div class="input-wrap">
        <img src="@/assets/image/index/sousuo.png" alt="" class="search-icon"/>
        <el-autocomplete
          ref="autocompleteRef"
          style="width: 100%"
          v-model="keyword"
          value-key="name"
          :popper-append-to-body="false"
          :placeholder="$t('找货源/商品/供应商/求购')"
          popper-class="cus-popper"
          :fetch-suggestions="querySearch"
          @select="handleSelect"
        >
          <template slot-scope="{ item }">
            <div v-if="!item.isHistory" class="data-item">
              <span class="van-ellipsis">{{ item.name }}</span>
            </div>
            <div v-if="item.isHistory" class="history-wrap">
              <div class="history-top">
                <span>{{ item.name }}</span>
                <div class="del" @click="emptyHandle">
                  <van-icon name="delete-o" color="#999" size="12"/>
                  <span>{{ $t("清除") }}</span>
                </div>
              </div>
              <ul class="history-list">
                <li v-for="(v, i) in searchHistory1" :key="i" @click.stop="historyHandle(v)">{{ v }}</li>
              </ul>
            </div>
          </template>
        </el-autocomplete>
        <van-button size="small" color="#d62014" style="width: 83px;border-radius: 4px;font-size: 14px" @click="historyHandle(keyword)">{{
            $t('搜索')
          }}
        </van-button>
      </div>
    </div>
  </van-popup>
</template>

<script>
import {Popup, Icon, Field} from 'vant';
import {Autocomplete} from 'element-ui'
import {searchSeller} from "@/API/common";
import {EventBus} from "@/utils/eventBus";

export default {
  name: "Search",
  components: {
    [Popup.name]: Popup,
    [Icon.name]: Icon,
    [Field.name]: Field,
    [Autocomplete.name]: Autocomplete,
  },
  data() {
    return {
      popupShow: false,
      keyword: '',
      listData: [],
      tipsData: [],
      searchHistory1: []
    }
  },
  mounted() {
    this.searchHistory1 =
      JSON.parse(localStorage.getItem("searchHistory1")) || [];
    this.searchHistory1 = [...new Set(this.searchHistory1)];
  },

  methods: {
    show() {
      this.popupShow = true
    },
    hide() {
      this.popupShow = false
      this.$emit('close')
    },
    querySearch(queryString, cb) {
      const emptyArr = [
        {
          name: this.$t('暂无数据'),
          isEmpty: true,
        },
        {
          name: this.$t('历史搜索'),
          isEmpty: true,
          isHistory: true,
        }
      ]
      this.listData = []
      if (this.keyword) {
        let lang = localStorage.getItem("lang");
        lang = lang.replace(/"/g, "");
        searchSeller({keyword: this.keyword, lang})
          .then((res) => {
            const shopItem = {
              keyword: this.keyword,
              name: `"${this.keyword}" ${this.$t("相关的店铺")}`,
              isShop: true,
            };
            if (res.goodsList.length) {
              this.listData = [shopItem, ...res.goodsList];
              cb(this.listData);
            } else {
              cb([shopItem, ...emptyArr, ...this.tipsData]);
            }
          })
          .catch(() => {
            cb([...emptyArr, ...this.tipsData])
          });
      } else {
        cb([...emptyArr, ...this.tipsData])
      }
    },
    handleSelect(item) {
      if (item.isEmpty) {
        this.keyword = ''
        return;
      }
      if (item.isHistory) {
        return
      }
      if (item.isShop) {
        this.keyword = ''
      }
      this.searchHistory1.unshift(item.isShop ? item.keyword : item.name);
      this.searchHistory1 = [...new Set(this.searchHistory1)];
      localStorage.setItem(
        "searchHistory1",
        JSON.stringify(this.searchHistory1)
      )
      this.hide()
      if (this.$route.path === '/Search') {
        EventBus.$emit('eventGoToSearch', {keyword: item.isShop ? item.keyword : item.name, isShop: item.isShop})
      } else {
        this.$router.push({
          path: '/Search',
          query: {
            keyword: item.isShop ? item.keyword : item.name,
            isShop: item.isShop
          }
        })
      }
    },
    historyHandle(v) {
      if (this.isAllSpaces(v)) {
        return
      }
      this.keyword = v
      this.hide()
      if (this.$route.path === '/Search') {
        EventBus.$emit('eventGoToSearch', {keyword: v, isShop: false})
      } else {
        this.$router.push({
          path: '/Search',
          query: {
            keyword: v,
            isShop: false
          }
        })
      }
    },
    emptyHandle() {
      this.$store.dispatch("clearSearchHistory");
      localStorage.removeItem("searchHistory1");
      this.searchHistory1 = [];
    },
    isAllSpaces(str) {
      return str.match(/^ *$/) !== null;
    }
  },
};
</script>
<style lang="scss">
.cus-popper{
  width: 80% !important;
}
</style>
<style lang="scss" scoped>
.popup-wrap {
  padding: 20px;

  .top-wrap {
    display: flex;
    justify-content: space-between;

    > span {
      font-size: 26px;
      text-align: center;
      flex: 1;
    }
  }

  .search-icon {
    width: 18px;
    height: 18px;
  }
}

.input-wrap {
  background-color: #FFF;
  margin-top: 20px;
  border-radius: 4px;
  border: 1px solid #DCDFE6;
  display: flex;
  align-items: center;
  padding: 0 15px;
}

.data-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.history-wrap{
  .history-top{
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    >span{
      color: #333333;
    }
    .del {
      display: flex;
      align-items: center;

      > span {
        font-size: 12px;
        color: #999;
        margin-left: 5px;
      }
    }
  }
  .history-list{
    display: flex;
    flex-wrap: wrap;
    >li{
      border-radius: 5px;
      background: #f6f6f6;
      margin-right: 10px;
      margin-bottom: 10px;
      text-align: center;
      padding: 2px 15px;
      color: #999999;
      font-size: 12px;
    }
  }
}

::v-deep {
  .el-input__inner {
    border: 0;
  }
}
</style>
